<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">


      <a-form-item class="smart-query-form-item" label="出库单号">
        <a-input v-model:value="queryForm.deliveryKey" placeholder="请输入出库单号" style="width: 160px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="机器信息">
        <a-input v-model:value="queryForm.keyword" placeholder="请输入机器编码/序列号/IMEI" style="width: 260px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="物流单号">
        <a-input v-model:value="queryForm.expno" placeholder="请输入物流单号" style="width: 160px"/>
      </a-form-item>

      <a-form-item class="smart-query-form-item" label="物流公司">
        <a-select v-model:value="queryForm.expType" allowClear placeholder="选择物流公司" style="width: 160px">
          <a-select-option :value="1">顺丰快递</a-select-option>
          <a-select-option :value="2">其他快递</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item class="smart-query-form-item" label="出库单状态">
        <a-select v-model:value="queryForm.status" allowClear placeholder="选择出库单状态" style="width: 160px">
          <a-select-option :value="0">已作废</a-select-option>
          <a-select-option :value="1">待线下配送</a-select-option>
          <a-select-option :value="2">待通知快递</a-select-option>
          <a-select-option :value="3">待快递上门</a-select-option>
          <a-select-option :value="4">已出库</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item class="smart-query-form-item" label="出库单类型">
        <a-select v-model:value="queryForm.deliveryType" allowClear placeholder="选择出库单类型" style="width: 160px">
          <a-select-option :value="1">回收退货</a-select-option>
          <a-select-option :value="2">第三方销售</a-select-option>
          <a-select-option :value="3">线下销售</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item class="smart-query-form-item" label="出库方式">
        <a-select v-model:value="queryForm.deliveryWay" allowClear placeholder="选择出库方式" style="width: 160px">
          <a-select-option :value="1">快递邮寄</a-select-option>
          <a-select-option :value="2">线下配送</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="关联单号">
        <a-input v-model:value="queryForm.orderKey" placeholder="请输入订单编号" style="width: 160px"/>
      </a-form-item>

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button type="primary" @click="resetPageNumAjaxQuery">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card :bordered="false" :hoverable="true" size="small">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button size="small" type="primary" @click="add()">
          <template #icon>
            <PlusOutlined/>
          </template>
          新增出库单
        </a-button>
        <a-button size="small" type="primary" @click="informExpress()">
          通知快递
        </a-button>
        <a-button size="small" type="primary" @click="printExpress()">
          打印面单
        </a-button>
        <a-button size="small" type="primary" @click="submitOutStorage()">
          出库
        </a-button>
      </div>
    </a-row>

    <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: rowSelectionChange }"
        :scroll="{ x: 1800 }"
        bordered
        rowKey="id"
        size="small"
    >
      <template #bodyCell="{ column, record, text }">

        <template v-if="column.dataIndex === 'expno'">
          {{text||'-'}}
        </template>
        <template v-if="column.dataIndex === 'deliveryType'">
          {{ DELIVERYTYPE[text] }}
        </template>
        <template v-if="column.dataIndex === 'deliveryWay'">
          {{ text == 1 ? '快递邮寄' : '线下配送' }}
        </template>
        <template v-if="column.dataIndex === 'expType'">
          {{ text == 1 ? '顺丰快递' : '其他快递' }}
        </template>
        <template v-if="column.dataIndex === 'freightFlag'">
          {{ text == 0 ? '我司承担' : '用户承担' }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          {{ STATUS[text] }}
        </template>

        <template v-if="column.dataIndex === 'exparea'">
          {{ text.split('@').join(' ') }} {{record.expdtl}}
        </template>

        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button type="link" @click="toDetail(record)">查看</a-button>
            <a-button v-if="record.status!==0" danger type="link" @click="confirmCancellationDelivery(record.id)">作废
            </a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :defaultPageSize="queryForm.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(total) => `共${total}条`"
          :total="total"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
      />
    </div>
  </a-card>

  <!--  添加和修改对话框-->
  <a-modal :title="`${formData.id?'编辑':'新增'}货架`" :visible="modalVisible" @cancel="onClose" @ok="save">
    <a-form ref="formRef" :label-col="labelCol" :model="formData" :rules="rules" :wrapper-col="wrapperCol">
      <a-form-item label="货架名称" name="rackName">
        <a-input v-model:value="formData.rackName" placeholder="请输入货架名称"/>
      </a-form-item>
      <a-form-item label="所属仓储区" name="storageId">
        <a-select v-model:value="formData.storageId"
                  :field-names="{label: 'storageName',value: 'id'}"
                  :filter-option="filterAreaOption"
                  :options="storageAreaOptions"
                  allowClear placeholder="选择仓储区" show-search style="width: 160px">
        </a-select>
      </a-form-item>
      <a-form-item label="备注">
        <a-textarea v-model:value="formData.bak" :maxlength="100" placeholder="请输入备注" show-count/>
      </a-form-item>
    </a-form>
  </a-modal>


  <printer ref="printerRef"></printer>
</template>


<script setup>
import {PAGE_SIZE, PAGE_SIZE_OPTIONS} from "/@/constants/common-const";
import {nextTick, onMounted, reactive, ref} from "vue";
import {smartSentry} from "/@/lib/smart-sentry";
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const";
import TableOperator from "/@/components/support/table-operator/index.vue";
import {message, Modal} from "ant-design-vue";
import {SmartLoading} from '/@/components/framework/smart-loading';
import {useRouter} from 'vue-router';
import _ from "lodash";
import {storageRackApi} from "/@/views/business/storage/storage-rack";
import {storageAreaApi} from "/@/views/business/storage/storage-area";
import {deliveryOrderApi} from "/@/views/business/storage/delivery-order";
import Printer from "/@/views/business/printer/printer.vue";


const printerRef = ref();
const router = useRouter();

const columns = ref([
  {
    align: 'center',
    title: '出库单号',
    dataIndex: 'deliveryKey',
    width: 80,
  },
  {
    align: 'center',
    title: '出库单类型',
    dataIndex: 'deliveryType',
    width: 80,
  },
  {
    align: 'center',
    title: '出库单状态',
    dataIndex: 'status',
    width: 80,
  },
  {
    align: 'center',
    title: '出库方式',
    dataIndex: 'deliveryWay',
    width: 80,
  },
  {
    align: 'center',
    title: '出库数量',
    dataIndex: 'machineNum',
    width: 80,
  },
  {
    align: 'center',
    title: '邮费承担',
    dataIndex: 'freightFlag',
    width: 80,
  },
  {
    align: 'center',
    title: '物流单号',
    dataIndex: 'expno',
    width: 80,
  },
  {
    align: 'center',
    title: '物流公司',
    dataIndex: 'expType',
    width: 80,
  },
  {
    align: 'center',
    title: '收件人姓名',
    dataIndex: 'lnker',
    width: 80,
  },
  {
    align: 'center',
    title: '收件人联系方式',
    dataIndex: 'lnktel',
    width: 80,
  },
  {
    align: 'center',
    title: '收件地址',
    dataIndex: 'exparea',
    width: 180,
  },
  {
    align: 'center',
    title: '创建时间',
    dataIndex: 'createTime',
    width: 120,
  },
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    width: 80,
    fixed: 'right'
  },
]);
const DELIVERYTYPE = {
  1: '回收退货',
  2: '第三方销售',
  3: '线下销售',
}
const STATUS = {
  0: '已作废',
  1: '待线下配送',
  2: '待通知快递',
  3: '待快递上门',
  4: '已出库',
}
// 组件ref
const formRef = ref();
const labelCol = {style: {width: '150px'}};
const wrapperCol = {span: 14};
const rules = {
  rackName: [{required: true, message: ''}],
  storageId: [{required: true, message: ''}],
};
let iconImgList = reactive({arr: []});
let quotationImgList = reactive({arr: []});
let modalVisible = ref(false);
const formDataDefault = {
  id: undefined,
  rackName: undefined,
  storageId: undefined,
  bak: '',
};

let formData = reactive({...formDataDefault});

const queryFormDataDefault = {
  deliveryKey: undefined,
  keyword: undefined,
  orderKey: undefined,
  expno: undefined,
  expType: undefined,
  status: undefined,
  deliveryType: undefined,
  deliveryWay: undefined,
  pageNum: 1,
  pageSize: PAGE_SIZE,
};
const queryForm = reactive({...queryFormDataDefault});
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref();

const storageAreaOptions = ref([]);

let selectedRows = [];
const selectedRowKeys = ref([]);

// 重置查询条件
function resetQuery() {
  Object.assign(queryForm, queryFormDataDefault);
  ajaxQuery();
}

onMounted(async () => {
  let responseModel = await storageAreaApi.queryPage({
    pageNum: 1,
    pageSize: 200,
  });
  storageAreaOptions.value = responseModel.data.list;
  ajaxQuery();
});

function resetPageNumAjaxQuery() {
  queryForm.pageNum = 1;
  ajaxQuery();
}

// 查询
async function ajaxQuery() {
  selectedRows = [];
  selectedRowKeys.value = [];
  try {
    tableLoading.value = true;
    let responseModel = await deliveryOrderApi.queryPage(queryForm);
    const list = responseModel.data.list;
    total.value = responseModel.data.total;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

function rowSelectionChange(keyArray, selected) {
  console.log(`selectedRowKeys: ${keyArray}`, 'selectedRows: ', selected);
  selectedRowKeys.value = keyArray;
  selectedRows = selected;
}

function update(record) {
  modalVisible.value = true;
  Object.assign(formData, record);
}

// 添加
function add() {
  router.push({path: '/storage/delivery-order-add'});
}

function onClose() {
  Object.assign(formData, formDataDefault);
  iconImgList.arr = [];
  quotationImgList.arr = [];
  modalVisible.value = false;
  nextTick(() => {
    formRef.value.clearValidate();
  });
}

// 保存
async function save() {
  if (!formData.rackName || formData.rackName.trim() === '') {
    return message.error('请输入货架名称');
  }
  if (!formData.storageId) {
    return message.error('请选择所属仓储区');
  }
  SmartLoading.show();
  const form = _.cloneDeep(formData)
  try {
    if (form.id) {
      await storageRackApi.update(form);
    } else {
      await storageRackApi.add(form);
    }
    message.success(`${form.id ? '修改' : '添加'}成功`);
    ajaxQuery();
    onClose();
  } catch (error) {
    smartSentry.captureError(error);
  } finally {
    SmartLoading.hide();
  }
}

// 删除
function confirmCancellationDelivery(record) {
  Modal.confirm({
    title: '提示',
    content: '确定要作废该出库单吗?',
    okText: '作废',
    okType: 'danger',
    onOk() {
      cancellationDelivery(record);
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}


// 输入仓储区过滤
function filterAreaOption(input, option) {
  return option.modelName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

function informExpress() {
  if (!selectedRows.length) {
    return message.error('请选择要操作的数据')
  }
  deliveryOrderApi.informExpress(selectedRows.map(i => i.id).join(',')).then(res => {
    message.success(res.data)
    selectedRows = [];
    selectedRowKeys.value = [];
  })
}

function printExpress() {
  if (!selectedRows.length) {
    return message.error('请选择要打印的数据')
  }
  const ids = [];
  selectedRows.forEach(item => {
    if (item.status !== 3 || !item.expno) {
    } else {
      ids.push(item.id)
    }
  });
  selectedRows = [];
  selectedRowKeys.value = [];
  if (!ids.length) {
    return message.warn('没有可打印的数据');
  }
  ids.forEach(id => {
    printerRef.value.printExpressInfo(id);
  })
}

function submitOutStorage() {
  if (!selectedRows.length) {
    return message.error('请选择要出库的数据');
  }
  Modal.confirm({
    title: '提示',
    content: '确认后出库单状态变为已出库',
    okText: '出库',
    onOk() {
      deliveryOrderApi.outStorage(selectedRows.map(i => i.id).join(',')).then(res => {
        message.success('出库成功')
        selectedRows = [];
        selectedRowKeys.value = [];
        ajaxQuery();
      })
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

function cancellationDelivery(id) {
  deliveryOrderApi.cancellationDelivery(id).then(() => {
    message.success('操作成功');
    ajaxQuery();
  })
}
function toDetail(record) {
  router.push({path: '/storage/delivery-order-detail', query: {id: record.id}});
}
</script>

<style lang="less" scoped>

</style>